package com.android.test.util;

public class SQLUtil {
    private static final String AND = " AND ";;
    private static final String CMD_AND = "(%s) AND (%s)";
    private static final String CMD_OR = "(%s) OR (%s)";
    private static final String CMD_SELECT = "%s=?";
    private static final String OR = " OR ";

    public static String and(String... params) {
	String CMD_AND_TEMP = CMD_AND;
	if (params.length <= 1)
	    return "";
	else {
	    int index = 0;
	    Object[] localObject = new Object[params.length];
	    for (Object param : params) {
		localObject[index] = param;
		if (index > 1) {
		    CMD_AND_TEMP += " AND (%s)";
		}
		index++;
	    }

	    return String.format(CMD_AND_TEMP, localObject);
	}
    }

    public static String or(String... params) {
	String CMD_OR_TEMP = CMD_OR;
	if (params.length <= 1)
	    return "";
	else {
	    int index = 0;
	    Object[] localObject = new Object[params.length];
	    for (Object param : params) {
		localObject[index] = param;
		if (index > 1) {
		    CMD_OR_TEMP += " OR (%s)";
		}
		index++;
	    }
	    return String.format(CMD_OR_TEMP, localObject);
	}
    }

    public static String textFilterBuilder(String column, String text) {
	String mTextFilter = column + " = '" + text + "'";
	return mTextFilter;
    }

    public static String integerFilterBuilder(String column, int number) {
	String mIntegerFilter = column + " = " + number;
	return mIntegerFilter;
    }

    public static String getSelection(String field) {
	Object[] params = new Object[1];
	params[0] = field;
	return String.format(CMD_SELECT, params);
    }

    public static String getSelectionAnd(String[] fields) {
	return getSelection(AND, fields);
    }

    public static String getSelectionOr(String[] fields) {
	return getSelection(OR, fields);
    }

    private static String getSelection(String operation, String[] fields) {

	int length;
	if (fields != null) {
	    length = fields.length;
	} else {
	    return StringUtil.EMPTY_STRING;
	}

	StringBuilder stringBuilder = new StringBuilder();

	Object[] args = new Object[1];
	args[0] = fields[0];
	String str1 = String.format(CMD_SELECT, args);
	stringBuilder.append(str1);

	for (int n = 1; n < length; n++) {
	    stringBuilder.append(operation);
	    Object[] tmpargs = new Object[1];
	    tmpargs[0] = fields[n];
	    str1 = String.format(CMD_SELECT, tmpargs);
	    stringBuilder.append(str1);
	}

	return stringBuilder.toString();
    }
}